from django.contrib.auth.hashers import check_password,make_password
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView

from user.models import Users
from user.user_func import *


class Login(APIView):
    permission_classes = []
    authentication_classes = []
    def get(self,request):

        return render(request,'login.html')

    def post(self,request):
        req = request.data
        data={'code':400}
        user = Users.objects.filter(Q(username=req.get('username'))|Q(mobile=req.get('username'))).first()
        if user:
            if check_password(req.get('password'),user.password):
                data['code']=200
                data['token']=create_token(user)
            else:
                data['error']='no user'
        else:
            data['error']=' no  username or password'
        return JsonResponse(data)


class Register(APIView):
    permission_classes = []
    authentication_classes = []
    def get(self,request):
        return render(request,'register.html')
    def post(self,request):
        req = request.data
        print(req)
        data={}
        try:
            Users.objects.get(Q(username=req.get('username'))|Q(mobile=req.get('username'))|Q(username=req.get('username')))
            data['code']=400
        except:
            user=Users(username=req.get('username'),password=make_password(req.get('password')),mobile=req.get('mobile'))
            user.save()
            data['code']=200
            data['token'] = create_token(user)
        return JsonResponse(data)

class Bet(APIView):
    def get(self,request):
        return JsonResponse({'CODE':200})
    def post(self,request):
        return JsonResponse({'CODE':200})